package com.bblocks.common;

import com.bblocks.Interceptor.AccessRoleInterceptor;
import com.bblocks.Interceptor.AuthorizationInterceptor;
import com.bblocks.Interceptor.LogInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import javax.annotation.Resource;
import java.util.List;

/**
 * 通用mvc配置，统一几次此类即可完成配置（扫包请扫com.bblocks）
 * @author Jin
 * @version 1.0
 * @date 2022/03/14
 */
//@Configuration
public class ParentWebMvcConfigurer implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer {

	@Resource
	protected LogInterceptor logInterceptor;
	@Resource
	protected AuthorizationInterceptor authorizationInterceptor;
	@Resource
	protected AccessRoleInterceptor accessRoleInterceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
		//0、初始日志相关的初始（原则是第一个）
		registry.addInterceptor(logInterceptor);

        //1、初始用户的信息进request
        registry.addInterceptor(authorizationInterceptor);

        //定义排除swagger访问的路径配置
        String[] swaggerExcludes=new String[]{"/v2/api-docs","/doc.html","/swagger-ui.html","/swagger-resources/**","/webjars/**","/error"};

        //2. 角色判断
        registry.addInterceptor(accessRoleInterceptor);//拦截角色
    }
    
    //@Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // 是否支持安全证书
        config.addAllowedOrigin("*"); // 允许任何域名使用
        config.addAllowedHeader("*"); // 允许任何头
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        // Spring data jpa pageable的参数分解器（）
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
        //resolver.setOneIndexedParameters(true); //影响首页从0还是1，默认0，true则1
        argumentResolvers.add(resolver);
    }

}
